package cn.ycc1.boot3stream.controller;

import cn.ycc1.boot3stream.Person;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author ycc
 * @date 2024/5/9
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping("/test1")
    public String test1(){
        List<Person> list = new ArrayList<>();
        list.add(new Person("zhangsan", 18));
        list.add(new Person("lisi", 19));
        list.add(new Person("wangwu", 20));
        list.add(new Person("zhaoliu", 21));

        list.stream().forEach(System.out::println);
        list.stream().filter(person -> person.getAge() > 18).forEach(System.out::println);
        list.stream().map(Person::getName).forEach(System.out::println);
        List<String> names = list.stream().map(Person::getName).collect(Collectors.toList());
        System.out.println(names);
        return "test1";
    }

    @RequestMapping("/test2")
    public String test2(){
        List<Person> list = null;
        list = Optional.ofNullable(list).orElseGet(() -> {
            List<Person> list1 = new ArrayList<>();
            list1.add(new Person("zhangsan", 18));
            return list1;
        });
        list.stream().forEach(System.out::println);

        List<Person> list2 = null;
        list2 = Optional.ofNullable(list2).orElse(new ArrayList<>());
        System.out.println(list2);
        return "test2";
    }

    @RequestMapping("/test3")
    public String test3(){
        List<Person> list = null;
        if(Objects.nonNull(list)){
            System.out.println("list is not null");
        } else {
            System.out.println("list is null");
            System.out.println(list); // 这里输出null
            System.out.println(list.get(0).getName()); // 如果为null 这里报空指针异常
        }

        List<Person> list2 = null;
//        System.out.println(list2.get(0).getName());
        return "test3";
    }
}
